package cn.jussi.mvcproject.utils;

import java.security.MessageDigest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	private static final String KEY = ":cookie@jussi.com520!";

	/**
	 * 指令浏览器创建cookie的方法
	 * @param username	：放在cookie信息里的 用户名
	 * @param req
	 * @param resp	：调用addCookie方法的response对象
	 * @param sec	：设置cookie失效的时间，单位秒
	 */
	public static void createCookie(String username, HttpServletRequest req, HttpServletResponse resp, int sec) {
		Cookie userCookie = new Cookie("userKey", username);
		Cookie ssidCookie = new Cookie("ssid",md5Encrypt(username));
		userCookie.setMaxAge(sec);
		ssidCookie.setMaxAge(sec);
		resp.addCookie(userCookie);
		resp.addCookie(ssidCookie);
	}

	/**
	 * 单向加密方法
	 * @param ss	:等待加密的明文
	 * @return
	 */
	public static String md5Encrypt(String ss) {
		ss = ss==null? "":ss+KEY;
		//字典
		char[] md5Digest = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
		try {
			MessageDigest md = MessageDigest.getInstance("MD5"); //MD5	sha1
			byte[] ssArr = ss.getBytes();
			md.update(ssArr);	//把名文放到加密类MessageDigest的实例中
			byte[] mssArr = md.digest();//加密
			int len = mssArr.length;
			char[] str = new char[len*2];
			int k = 0;	
			for(int i=0; i<len; i++) {
				byte b = mssArr[i];
				str[k++] = md5Digest[b >>> 4 & 0xf];
				str[k++] = md5Digest[b & 0xf];
			}
			//System.out.println(new String(str));
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
